//
//  NDCircleContentView.m
//  JiMeiUnv
//
//  Created by devp on 14-9-5.
//  Copyright (c) 2014年 nd. All rights reserved.
//

#import "NDCircleContainView.h"

@interface NDCircleContentView ()
@property (nonatomic, assign) NDCircleContentViewState state;
@property (nonatomic, strong) UIActivityIndicatorView  *activityView;
@end

@implementation NDCircleContentView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self setup];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup {
    self.tintColor = [UIColor colorWithRed:63.0/255.0 green:157.0/255.0 blue:176.0/255.0 alpha:1];
    self.backgroundColor = [UIColor clearColor];
    
    _activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _activityView.hidden = YES;
    [self addSubview:_activityView];
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    
    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetLineWidth(context, 2.0);
    CGContextSetLineCap(context, kCGLineCapRound);
    CGContextSetStrokeColorWithColor(context, (_state == NDCircleContentViewStateLoading) ? [UIColor clearColor].CGColor :self.tintColor.CGColor);
    CGFloat startAngle = -M_PI/2;
    CGFloat step = 2*M_PI * self.progress;
    
    CGContextAddArc(context, self.center.x, self.center.y, self.contentSize.width/2-3, startAngle, startAngle+step, 0);
    
    CGContextStrokePath(context);
    
}

- (void)setProgress:(CGFloat)progress {
    if (_progress != progress) {
        _progress = progress;
        [self setNeedsDisplay];
    }
}

- (void)nd_refreshControl:(NDRefreshControl *)refreshControl scrollViewDraggedOffset:(CGFloat)offset progress:(CGFloat)progress {
    self.progress = progress;
}

- (void)nd_refreshControlWillTriggerRefresh:(NDRefreshControl *)refreshControl {
    _state = NDCircleContentViewStateLoading;
    
    [self showActivityIndicatorView:YES];
}

- (void)nd_refreshControlWillFinishRefresh:(NDRefreshControl *)refreshControl {
    _state = NDCircleContentViewStateFinish;
    
    [self showActivityIndicatorView:NO];
}

#pragma mark - private
- (void)showActivityIndicatorView:(BOOL)showFlag {
    if (showFlag) {
        if (!_activityView.isAnimating) {
            [_activityView startAnimating];
        }
        _activityView.hidden = NO;
    } else {
        if (_activityView.isAnimating) {
            [_activityView stopAnimating];
        }
        _activityView.hidden = YES;
    }
    _activityView.center = self.center;
    
    [self setNeedsDisplay];
}

@end
